import React, {
    PureComponent
} from 'react';

import {
    View,
    Text,
    Image,
    StyleSheet,
    TextInput
} from 'react-native';

import {
    File,
    Tip,
    CheckBox,
    Dialog,
    Press,
    Layout,
    Button,
    Choose,
    Loading,
    FastImage
} from './../../components';

import {
    Actions
} from 'react-native-router-flux';

import Ajax from './../../http';

import * as CONST from './../../const';
import Connect from './../../utils/connect';
import close_icon from './../../images/close.png';

interface Props {
    user:any,
    typeId:any,
    videoId:number,
    userId:number
    backUrl:string,
    commonActions:any
}

interface State {
    checked:boolean,
    imageList: any,
    content: string
}

import commonAction from './../../state/actions/common';
import * as commonTypes from './../../state/types/common';
const _placeholder = `Please tell the reason to report this member.`;

@Connect([`user`],{
    commonActions:commonAction
})
class Contact extends PureComponent<Props, State> {
    state = {
        checked:false,
        content: ``,
        imageList: []
    }

    static defaultProps = {
        user:{},
        videoId:0,
        userId:0,
        backUrl:``,
        typeId:``,
        commonActions:{}
    }

    get commonAction() {
        const {
            commonActions
        } = this.props;
        return commonActions;
    }

    get userState() {
        const {
            user
        } = this.props;
        return user;
    }

    get userInfo() {
        const {
            loginUser
        } = this.userState;
        return loginUser || {}
    }

    get email() {
        const {
            email
        } = this.userInfo;
        return email;
    }

    get fetchUrl() {
        const {
            videoId,
            userId
        } = this.props;

        return !videoId ?
            `report/user/${userId}` :
            `report/video`;
    }

    private uploadFile = async ({path}:any) => {
        const {
            imageList
        } = this.state;

        Loading.show();

        try {
            const item = (
                await Ajax.uploadImage(path)
            )
            imageList.push({
                ...item,
                path: path
            } as never)
            this.setState({
                imageList: [...imageList]
            })
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }
        Loading.close()
    }

    private _onDeleteRow = (i:number) => {
        const {
            imageList
        } = this.state;
        imageList.splice(i, 1);
        this.setState({
            imageList: [...imageList]
        })
    }

    get attachIds() {
        const {
            imageList
        } = this.state;
        return imageList.map(
            (item:any) => item.id
        )
    }

    private onSubmit = async () => {
        const {
            checked,
            content
        } = this.state;

        const {
            userId,
            videoId,
            typeId,
            backUrl
        } = this.props;

        Loading.show();

        const _query = !!videoId ? {
            videoId: videoId,
            reason: typeId
        } : {
            typeId: typeId,
            typeName: `report`
        }

        const _para = {
            ..._query,
            attachIds: this.attachIds,
            content:  `${content} | Support from: ${this.email}`
        }

        try {
            await (
                Ajax.post(this.fetchUrl, _para)
            )

            if(checked) {
                await this.commonAction[
                    commonTypes.blockUser
                ](userId);
            }

            Dialog.alert({
                title: `Tips`,
                showClose:false,
                message: `Report successful!`
            }).then(() => (
                Actions.popTo(backUrl)
            ))
        }
        catch (e) {
            Tip.warm({
                message: e.message
            })
        }
        Loading.close();
    }

    private _onContentChange = (text: string) => {
        this.setState({
            content: text
        })
    }

    get disabled() {
        const {
            content = ``
        } = this.state;
        return !content.trim();
    }

    private onSwitch = () => {
        const {
            checked
        } = this.state;
        this.setState({
            checked:!checked
        })
    }

    private renderImageItem = (
        item:any,i:number
    ) => {
        const node = (
            <Press
                value={i}
                style={styles.deleteRow}
                onPress={this._onDeleteRow}
            >
                <Image
                    source={close_icon}
                    style={styles.deleteImage}
                />
            </Press>
        )
        return (
            <View
                key={i}
                style={styles.fileStyle}
            >
                <FastImage
                    url={item.path}
                    style={styles.imageStyle}
                />
                {node}
            </View>
        )
    }

    render() {
        const {
            checked,
            content,
            imageList
        } = this.state;
        return (
            <Layout title="Report">
                <View style={styles.container}>
                    <View style={styles.item}>
                        <TextInput
                            value={content}
                            multiline={true}
                            style={styles.textArea}
                            placeholder={_placeholder}
                            placeholderTextColor="#61677C"
                            onChangeText={this._onContentChange}
                        />
                    </View>
                    <View style={styles.item}>
                        <Text style={styles.title}>
                            Attach screenshots as a proof
                        </Text>
                        <View style={styles.files}>
                            <File onChange={this.uploadFile}>
                                <Choose style={styles.chooseStyle}/>
                            </File>
                            {imageList.map(this.renderImageItem)}
                        </View>
                    </View>
                    <View style={styles.item}>
                        <Press style={styles.content} onPress={this.onSwitch}>
                            <CheckBox
                                checked={checked}
                                onChange={this.onSwitch}
                            />
                            <Text style={styles.label}>
                                Also block this member from contacting me
                            </Text>
                        </Press>
                    </View>
                    <Button
                        title="Send"
                        style={styles.submit}
                        onPress={this.onSubmit}
                        disabled={this.disabled}
                    />
                </View>
            </Layout>
        )
    }
}

export default Contact;

const styles = StyleSheet.create({
    container: {
        paddingVertical: 16
    },
    textArea: {
        padding: 16,
        height: 168,
        fontSize: 16,
        color: `#fff`,
        borderRadius: 4,
        backgroundColor: `#fff`,
        textAlignVertical: 'top'
    },
    item :{
        marginBottom:30
    },
    title:{
        fontSize:14,
        marginBottom:16,
        color:`#8A92AE`
    },
    submit: {
        marginTop: 20
    },
    files: {
        flexDirection: `row`
    },
    imageStyle: {
        width: 64,
        height: 64,
        borderRadius: 8,
        overflow: `hidden`
    },
    chooseStyle:{
        width: 64,
        height: 64,
        borderRadius: 8,
    },
    fileStyle: {
        marginLeft: 16
    },
    deleteRow: {
        top: -4,
        right: -4,
        width: 18,
        height: 18,
        borderRadius: 9,
        position: `absolute`,
        alignItems: `center`,
        justifyContent: `center`,
        backgroundColor: CONST.color
    },
    deleteImage: {
        width: 8,
        height: 8
    },
    content:{
        alignItems:`center`,
        flexDirection:`row`
    },
    label:{
        fontSize:14,
        marginLeft:6,
        color:`#8A92AE`
    }
}) as any;